<template>
  <el-form :inline="true" class="mb-4">
    <el-form-item label="权限名称">
      <el-input v-model="queryConditions.name" style="width: 200px" size="large" placeholder="请输入权限名称"
        :suffix-icon="Search" clearable />
    </el-form-item>
    <el-button type="primary" :icon="Search" @click="search">查询</el-button>
    <el-button type="primary" :icon="RefreshRight" @click="reset">重置</el-button>
  </el-form>

  <TestPage
    :table-data="formattedTableData"
    :columns="tableColumns"
    :current-page="pageNo"
    :total="allPage"
    :page-size="pageSize"
    @page-change="handlePageChange"
    @action="handleTableAction"
    @edit="handleEditAction"
    @delete="handleDeleteAction"
  />

  <el-dialog title="新增权限" v-model="showAddDialog" width="40%" :before-close="handleDialogClose">
    <AddPermission @submit-success="handleAddSuccess" @cancel="handleDialogClose" />
  </el-dialog>

  <el-dialog title="编辑权限" v-model="showEditDialog" width="40%" :before-close="handleDialogClose">
    <AddPermission :permission="editingPerm" @submit-success="handleEditSuccess" @cancel="handleDialogClose" />
  </el-dialog>
</template>

<script setup lang="ts">
import TestPage from '@/test/TestPage.vue'
import AddPermission from './AddPerm.vue'
import { Search, RefreshRight } from '@element-plus/icons-vue'
import { ref, reactive, computed } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import type { Permission } from '@/types/rs/Permission'
import request from '@/util/request'
const pageNo = ref(1)
const pageSize = ref(10)
const allPage = ref(0)

// 查询条件仅支持 name
const queryConditions = reactive({ name: '' })

const tableColumns = ref([
  { prop: 'id', label: '序号' },
  { prop: 'name', label: '权限名称' },
  { prop: 'purl', label: '权限路径' },
  { prop: 'is_delete', label: '删除状态' },
  { prop: 'createDate', label: '创建时间' },
  { prop: 'createUser', label: '创建人' },
  { prop: 'updateDate', label: '更新时间' },
  { prop: 'updateUser', label: '更新人' }
])

const tableData = ref<Permission[]>([])
const formattedTableData = computed(() =>
  tableData.value.map(item => ({
    ...item,
    is_delete: item.is_delete === 0 ? '正常' : '被删除'
  }))
)

const showAddDialog = ref(false)
const showEditDialog = ref(false)
const editingPerm = ref<Permission | null>(null)

function handlePageChange(newPage: number) {
  pageNo.value = newPage
  fetchData(newPage)
}

function handleTableAction(action: string) {
  if (action === 'add') showAddDialog.value = true
}

function handleEditAction(row: Permission) {
  editingPerm.value = { ...row }
  showEditDialog.value = true
}

async function handleDeleteAction(row: Permission) {
  try {
    await ElMessageBox.confirm('确定删除此权限？此操作不可恢复。', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await request.post(`per/perm/del?id=${row.id}`)
    ElMessage.success('删除成功')
    fetchData(pageNo.value)
  } catch (err) {
    ElMessage.error('删除失败')
    console.error(err)
  }
}

function handleAddSuccess() {
  showAddDialog.value = false
  fetchData(pageNo.value)
  ElMessage.success('新增权限成功')
}

function handleEditSuccess() {
  showEditDialog.value = false
  editingPerm.value = null
  fetchData(pageNo.value)
  ElMessage.success('更新权限成功')
}

function handleDialogClose() {
  ElMessageBox.confirm('确定关闭窗口？未保存的数据将丢失。', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    showAddDialog.value = false
    showEditDialog.value = false
  })
}

function search() {
  pageNo.value = 1
  fetchData(1)
}

function reset() {
  queryConditions.name = ''
  pageNo.value = 1
  fetchData(1)
}

async function fetchData(page: number) {
  try {
    const params = new URLSearchParams()
    params.append('pageNow', page.toString())
    params.append('pageSize', pageSize.value.toString())
    if (queryConditions.name) params.append('name', queryConditions.name)

    const res = await request.get('per/perm/getPage', { params })
    tableData.value = res.data.data.list || []
    allPage.value = res.data.data.total || 0
  } catch (err) {
    ElMessage.error('获取权限数据失败')
    tableData.value = []
    allPage.value = 0
    console.error(err)
  }
}

fetchData(1)
</script>

<style scoped>
.mb-4 { margin-bottom: 16px; }
</style>
